
<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品参数</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <!-- 警告区域 -->
      <el-alert center title="注意：只允许为三级分类设置" type="warning" effect="light" show-icon closable></el-alert>
      <!-- 选择商品分类区域 -->
      <el-row :gutter="20" style="margin:15px">
        <el-col :span="3">
          选择商品分类
        </el-col>
        <el-col :span="21">
          <!-- 选择商品分类的级联选择框 -->
          <el-cascader clearable :options="CateList" v-model="selectedKeys"
            :props="{ expandTrigger: 'hover', label:'cat_name',value:'cat_id'}" @change="handleChange">
          </el-cascader>
        </el-col>
      </el-row>
      <!-- tab页签区域 -->
      <el-tabs v-model="activeName" @tab-click="handletabClick">
        <el-tab-pane label="动态属性" name="many">
          <el-button @click="addCateDialogVisible=true" type="primary" :disabled="isBtnDisabled">添加动态属性</el-button>
          <el-table :data="manyTableData">
            <el-table-column type="expand">
              <template v-slot="{row}">
                <el-tag @close="handleRemove(row,index)" v-for="(item,index) in row.attr_vals" :key="index" closable>
                  {{item}}
                </el-tag>
                <el-input class="input-new-tag" v-if="row.inputVisible" v-model.trim="row.inputValue" ref="saveTagInput"
                  size="small" @keyup.enter.native="handleInputConfirm(row)" @blur="handleInputConfirm(row)">
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template v-slot='{row}'>
                <el-button size="mini" type="primary" icon="el-icon-edit" @click="showEditDialong(row)"></el-button>
                <el-button size="mini" type="danger" icon="el-icon-delete" @click="remove(row.attr_id)"></el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button @click="addCateDialogVisible=true" type="primary" :disabled="isBtnDisabled">添加静态属性</el-button>
          <el-table :data="onlyTableData">
            <el-table-column type="expand"></el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <el-button size="mini" type="primary" icon="el-icon-edit"></el-button>
              <el-button size="mini" type="danger" icon="el-icon-delete"></el-button>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加对话框 -->
    <el-dialog :title="'添加'+titleText" :visible.sync="addCateDialogVisible" width="30%" @close="handleCloce">
      <el-form ref="addFormRef" label-width="80px" :model="addForm" :rules="addFormRules">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="addCateDialogVisible = false">Cancel</el-button>
        <el-button type="primary" @click="addCate">OK</el-button>
      </span>
    </el-dialog>
    <!-- 修改对话框 -->
    <el-dialog :title="'修改'+titleText" :visible.sync="editCateDialogVisible" width="30%">
      <el-form ref="editFormRef" label-width="80px" :model="editForm" :rules="addFormRules">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="editCateDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveEditCate">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      inputVisible: false,
      inputValue: '',
      editCateDialogVisible: false,
      editForm: {},
      addForm: {
        attr_name: ''
      },
      addFormRules: {
        attr_name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' }
        ]
      },
      // 对话框隐藏
      addCateDialogVisible: false,
      manyTableData: [],
      onlyTableData: [],
      // 被激活的页签的名字
      activeName: 'many',
      // 存放所有商品分类列表的数据
      CateList: [],
      // 存放当前选中的三级分类
      selectedKeys: []
    }
  },
  methods: {
    async saveTags (row) {
      const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`, { attr_name: row.attr_name, attr_sel: this.activeName, attr_vals: row.attr_vals.join(' ') })
      if (res.meta.status !== 200) return this.$message.error('添加失败')
      this.$message.success('添加成功')
      row.inputValue = ''
      row.inputVisible = false
    },
    handleRemove (row, index) {
      row.attr_vals.splice(index, 1)
      this.saveTags(row)
    },
    async handleInputConfirm (row) {
      if (row.inputValue === '') {
        row.inputVisible = false
        return
      }
      row.attr_vals.push(row.inputValue)
      this.saveTags(row)
    },
    showInput (row) {
      row.inputVisible = true
      this.$nextTick(() => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    remove (id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$http.delete(`categories/${this.cateId}/attributes/${id}`)
        if (res.meta.status !== 200) return this.$message.error('删除失败')
        this.getParamsList()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    saveEditCate () {
      this.$refs.editFormRef.validate(async bool => {
        // if (!bool) return console.log('校验失败')
        const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${this.editForm.attr_id}`, { attr_name: this.editForm.attr_name, attr_sel: this.activeName })
        if (res.meta.status !== 200) return this.$message.error('添加失败')
        this.editCateDialogVisible = false
        this.getParamsList()
      })
    },
    showEditDialong (row) {
      this.editForm = { ...row }
      this.editCateDialogVisible = true
    },
    addCate () {
      this.$refs.addFormRef.validate(async bool => {
        if (!bool) return console.log('校验失败')
        const { data: res } = await this.$http.post(`categories/${this.cateId}/attributes`, { attr_sel: this.activeName, attr_name: this.addForm.attr_name })
        if (res.meta.status !== 201) return this.$message.error('添加失败')
        this.addCateDialogVisible = false
        this.getParamsList()
      })
    },
    handleCloce () {
      this.$refs.addFormRef.resetFields()
    },
    // 获取数据
    async getParamsList () {
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, { params: { sel: this.activeName } })
      if (res.meta.status !== 200) return this.$message.error('获取失败')
      console.log(res.data)
      // 在赋值之前，先把数据二次加工一下
      res.data.forEach(item => {
        if (item.attr_vals === '') {
          item.attr_vals = []
        } else {
          item.attr_vals = item.attr_vals.split(' ')
        }
        item.inputVisible = false
        item.inputValue = ''
      })
      if (this.activeName === 'only') {
        this.onlyTableData = res.data
      } else {
        this.manyTableData = res.data
      }
    },

    handletabClick () {
      console.log(this.activeName)
      this.getParamsList()
    },
    // 级联选择框选中项变化触发
    handleChange () {
      if (this.selectedKeys.length !== 3) {
        this.manyTableData = this.onlyTableData = this.selectedKeys = []
        return
      }
      // 如果选中的是第三项则获取数据
      this.getParamsList()
    },
    // 获取所有商品分类列表
    async getCateList () {
      const { data: res } = await this.$http.get('categories')
      this.CateList = res.data
    }
  },
  computed: {
    titleText () {
      return this.activeName === 'only' ? '静态属性' : '动态属性'
    },
    isBtnDisabled () {
      return this.selectedKeys.length !== 3
    },
    cateId () {
      if (this.selectedKeys.length === 3) {
        return this.selectedKeys[2]
      }
      return null
    }
  },
  watch: {},
  filters: {},
  components: {},
  created () {
    this.getCateList()
  },
  mounted () { }
}
</script>

<style scoped lang='less'>
.el-tag {
  margin: 20px;
}
.input-new-tag {
  width: 100px;
  margin-left: 10px;
}
</style>
